package com.turtle.security.security.handle;

import com.alibaba.fastjson.JSON;
import com.turtle.security.common.constant.HttpStatus;
import com.turtle.security.common.utils.ApiResult;
import com.turtle.security.common.utils.ServletUtils;
import com.turtle.security.security.dto.AuthUserDTO;
import com.turtle.security.security.service.TokenOperatorService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 退出登录成功处理
 *
 * @author turtle
 * date: 2020-05-12
 */
@Configuration
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class LogoutSuccessHandle implements LogoutSuccessHandler {
    private final TokenOperatorService tokenOperatorService;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        AuthUserDTO authUser = tokenOperatorService.getAuthUserByToken(httpServletRequest);
        if (authUser != null) {
            String userId = authUser.getUserId().toString();
            // 从缓存种删除用户信息
            tokenOperatorService.delAuthUser(userId);
        }
        ServletUtils.renderString(httpServletResponse, JSON.toJSONString(ApiResult.unauthorized(HttpStatus.SUCCESS, "退出成功")));
    }
}
